package com.yxq.mdt.app.modules.personal.ui.anchor;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.bottomsheet.SoundVoiceBottomSheetDialogFragment;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.personal.bean.OpenChatQuestBean;
import com.yxq.mdt.app.modules.personal.bean.RealNameResultBean;
import com.yxq.mdt.app.modules.personal.model.RealNameModel;
import com.yxq.mdt.app.modules.personal.presenter.IRealNameContract;
import com.yxq.mdt.app.modules.personal.presenter.RealNamePresenter;
import com.yxq.mdt.app.modules.video.ui.activity.DisplayVideoAc;
import com.yxq.mdt.app.utils.GlideEngine;
import com.yxq.mdt.app.utils.MediaPlayerHelper;
import com.yxq.mdt.app.utils.StringUtils;
import com.yxq.mdt.app.widgets.CheckAudioPermission;
import com.yxq.mdt.app.widgets.OssHelper;
import com.yxq.mdt.app.widgets.tagview.Tag;
import com.yxq.mdt.app.widgets.tagview.TagView;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 开通密聊
 */
public class PersonalOpenChatAc extends BaseActivity<RealNamePresenter> implements IRealNameContract.View {

    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.search_tag_view)
    TagView searchTagView;
    @BindView(R.id.authentication_succeed_name)
    TextView authenticationSucceedName;
    @BindView(R.id.open_chat_voice_img)
    CheckBox openChatVoiceImg;
    @BindView(R.id.authentication_succeed_number)
    TextView authenticationSucceedNumber;
    @BindView(R.id.open_chat_video_img)
    CheckBox openChatVideoImg;
    @BindView(R.id.open_chat_uploading_img)
    ImageView openChatUploadingImg;
    @BindView(R.id.real_certification_immediately)
    TextView realCertificationImmediately;
    @BindView(R.id.open_chat_uploading_lint)
    LinearLayout openChatUploadingLint;
    @BindView(R.id.open_chat_uploading_img_audio)
    TextView openChatUploadingImgAudio;
    @BindView(R.id.open_chat_uploading_audio_lint)
    LinearLayout openChatUploadingAudioLint;
    @BindView(R.id.publish_del_voice)
    ImageView publishDelVoice;
    @BindView(R.id.publish_add_voice_time)
    TextView publishAddVoiceTime;
    @BindView(R.id.publish_save_voice)
    LinearLayout publishSaveVoice;
    @BindView(R.id.publish_start_play)
    RelativeLayout publishStartPlay;
    @BindView(R.id.publish_note)
    ImageView publishNote;
    @BindView(R.id.open_chat_uploading_img_del)
    ImageView openChatUploadingImgDel;
    private int channelIndex = 0;
    private String playYime;
    String[] test = new String[]{
            "情侣匹配", "虚拟恋人", "体贴甜心", "情话大师", "调皮可爱", "女神视频", "晚安电台", "甜蜜约会"};
    private String videoUrl;//视频文件路径
    private String audioUrl;//音频文件路径
    private int audioUrlId = -1;//音频文件id
    //    private int videoUrlId = -1;//视频文件id
    CountDownTimer countDownTimer;
    public boolean isVoiceStart = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_personal_open_chat;
    }

    @Override
    public void initView() {

        //开启为视频
        openChatVideoImg.setOnCheckedChangeListener((compoundButton, b) -> {
            if (openChatVideoImg.isChecked()) {
                openChatUploadingLint.setVisibility(View.VISIBLE);
//                openChatUploadingAudioLint.setVisibility(View.GONE);
//                openChatVoiceImg.setChecked(false);
            }
//            else {
//                openChatUploadingLint.setVisibility(View.GONE);
//                openChatUploadingAudioLint.setVisibility(View.VISIBLE);
//                openChatVoiceImg.setChecked(true);
//            }

        });
        //开启为语音
        openChatVoiceImg.setOnCheckedChangeListener((compoundButton, b) -> {
            if (openChatVoiceImg.isChecked()) {
//                openChatUploadingLint.setVisibility(View.GONE);
                openChatUploadingAudioLint.setVisibility(View.VISIBLE);
//                openChatVideoImg.setChecked(false);
            }
//            else {
//                openChatUploadingLint.setVisibility(View.VISIBLE);
//                openChatUploadingAudioLint.setVisibility(View.GONE);
//                openChatVideoImg.setChecked(true);
//            }

        });
        //删除语音
        publishDelVoice.setOnClickListener(view -> {
            publishSaveVoice.setVisibility(View.GONE);
            publishDelVoice.setVisibility(View.GONE);
            openChatUploadingImgAudio.setVisibility(View.VISIBLE);
            audioUrl = null;
        });
        //删除视频
        openChatUploadingImgDel.setOnClickListener(view -> {
            openChatUploadingImg.setVisibility(View.VISIBLE);
            openChatUploadingImg.setImageResource(R.mipmap.icon_anchor_upload);
            openChatUploadingImg.setOnClickListener(view1 -> setPublishSelectVideo());
        });
        publishStartPlay.setOnClickListener(view -> {
            if (isVoiceStart) {
                isVoiceStart = false;
                MediaPlayerHelper.realese();
                countDownTimer.onFinish();
            } else {
                isVoiceStart = true;
                MediaPlayerHelper.playSound(audioUrl, mediaPlayer -> isVoiceStart = false);
                getTime(playYime);
                countDownTimer.start();
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    private void getTime(String playTime) {
        publishNote.setImageResource(R.mipmap.voice_note_new);
        countDownTimer = new CountDownTimer(Integer.parseInt(playTime) * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                publishAddVoiceTime.setText(millisUntilFinished / 1000 + "″");
                publishDelVoice.setVisibility(View.GONE);
            }

            @Override
            public void onFinish() {
                publishAddVoiceTime.setText(playYime + "″");
                publishNote.setImageResource(R.mipmap.voice_note);
                publishDelVoice.setVisibility(View.VISIBLE);
            }
        };
    }

    private void initTags() {
        searchTagView.removeAllTags();
        for (int i = 0; i < test.length; i++) {
            Tag tag = new Tag(test[i]);
            if (channelIndex == i) {
                tag.tagTextColor = getResources().getColor(R.color.color_font_black);
                tag.layoutColor = getResources().getColor(R.color.color_font_yellow);
                tag.layoutColorPress = getResources().getColor(R.color.color_font_yellow);
                tag.layoutBorderColor = getResources().getColor(R.color.color_font_yellow);
            } else {
                tag.tagTextColor = getResources().getColor(R.color.color_font_black);
                tag.layoutColor = getResources().getColor(R.color.gray);
                tag.layoutColorPress = getResources().getColor(R.color.color_font_yellow);
                tag.layoutBorderColor = getResources().getColor(R.color.gray);
            }
            tag.radius = 50f;
            tag.tagTextSize = 14f;
            tag.layoutBorderSize = 10f;
            tag.isDeletable = false;
            searchTagView.addTag(tag);
        }
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new RealNamePresenter(this, new RealNameModel());
        showLoadingDialog();
        mPresenter.getCardNoAndName();
    }

    @OnClick({R.id.real_certification_immediately, R.id.open_chat_uploading_img, R.id.open_chat_uploading_img_audio})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.real_certification_immediately://开通密聊
                openChat();
                break;
            case R.id.open_chat_uploading_img://选择视频
                setPublishSelectVideo();
                break;
            case R.id.open_chat_uploading_img_audio://选择音频
                //检测是否有录音权限
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    Log.i(TAG, "默认无录音权限");
                    if (Build.VERSION.SDK_INT >= 23) {
                        requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 1001);
                    }
                } else {
                    SoundVoiceBottomSheetDialogFragment soundVoiceBottomSheetDialogFragment = new SoundVoiceBottomSheetDialogFragment("s");
                    soundVoiceBottomSheetDialogFragment.show(getSupportFragmentManager(), "soundVoiceBottomSheetDialogFragment");
                    soundVoiceBottomSheetDialogFragment.setSoundVoiceBottomSheetDialogFragmentTime((time, path) -> {//返回的时间和所在路径.
                        if (TextUtils.isEmpty(time)) {
                            publishAddVoiceTime.setText("");
                        } else {
                            publishAddVoiceTime.setText(time + "″");
                            audioUrl = path;
                            playYime = time;
                            Log.e("path", path);
                            openChatUploadingImgAudio.setVisibility(View.GONE);
                            publishSaveVoice.setVisibility(View.VISIBLE);
                            publishDelVoice.setVisibility(View.VISIBLE);
                        }
                    });
                }
                break;
        }
    }

    /**
     * 开通密聊
     */
    private void openChat() {
        OpenChatQuestBean openChatQuestBean = new OpenChatQuestBean();
        openChatQuestBean.setMlChannel((channelIndex + 1));//频道ID
        openChatQuestBean.setSoundsVideoStatus(openChatVoiceImg.isChecked() ? 1 : 2);
        if (openChatVoiceImg.isChecked()) {
            if (audioUrl == null) {
                ToastUtils.showShort("请上传音频介绍");
                return;
            }
            showLoadingDialog();
            if (audioUrl.startsWith("http")) {
                //音频
                if (audioUrlId != -1) {
                    OpenChatQuestBean.AudioFileBean audioFileBean = new OpenChatQuestBean.AudioFileBean(audioUrlId + "", audioUrl);
                    audioFileBean.setFileLength(StringUtils.getMediaDurationMill(audioUrl) + "");
                    openChatQuestBean.setAudioFile(audioFileBean);
                } else {
                    OpenChatQuestBean.AudioFileBean audioFileBean = new OpenChatQuestBean.AudioFileBean(audioUrl);
                    audioFileBean.setFileLength(StringUtils.getMediaDurationMill(audioUrl) + "");
                    openChatQuestBean.setAudioFile(audioFileBean);
                }
                mPresenter.saveOpenChat(JSON.toJSONString(openChatQuestBean));
                return;
            }
            uploadFile(audioUrl, data -> {
                //音频
                if (audioUrlId != -1) {
                    OpenChatQuestBean.AudioFileBean audioFileBean = new OpenChatQuestBean.AudioFileBean(audioUrlId + "", data);
                    audioFileBean.setFileLength(StringUtils.getMediaDurationMill(audioUrl) + "");
                    openChatQuestBean.setAudioFile(audioFileBean);
                } else {
                    OpenChatQuestBean.AudioFileBean audioFileBean = new OpenChatQuestBean.AudioFileBean(data);
                    audioFileBean.setFileLength(StringUtils.getMediaDurationMill(audioUrl) + "");
                    openChatQuestBean.setAudioFile(new OpenChatQuestBean.AudioFileBean(data));
                }

                mPresenter.saveOpenChat(JSON.toJSONString(openChatQuestBean));
            });
        } else if (openChatVideoImg.isChecked()) {
            if (videoUrl == null) {
                ToastUtils.showShort("请上传视频介绍");
                return;
            }
            showLoadingDialog();
            if (videoUrl.startsWith("http")) {
                //视频
                openChatQuestBean.setVideoDetails(videoUrl);
                mPresenter.saveOpenChat(JSON.toJSONString(openChatQuestBean));
                return;
            }
            uploadFile(videoUrl, data -> {
                //视频
                openChatQuestBean.setVideoDetails(data);
                mPresenter.saveOpenChat(JSON.toJSONString(openChatQuestBean));
            });

        } else {
            openChatQuestBean.setSoundsVideoStatus(0);
            mPresenter.saveOpenChat(JSON.toJSONString(openChatQuestBean));
        }

    }

    /**
     * 打开视频选择器
     */
    private void setPublishSelectVideo() {
        //视频
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofVideo())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)//选择最多一个视频
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .previewVideo(true)
                .recordVideoSecond(30)
                .forResult(PictureConfig.TYPE_VIDEO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.TYPE_VIDEO:
                    List<LocalMedia> images = PictureSelector.obtainMultipleResult(data);
                    videoUrl = images.get(0).getPath();
                    openChatUploadingImg.setVisibility(View.VISIBLE);
                    GlideHelper.setLoadRoundImage(mActivity, String.valueOf(Uri.fromFile(new File(videoUrl))), 0, openChatUploadingImg);
                    openChatUploadingImgDel.setVisibility(View.VISIBLE);
                    openChatUploadingImg.setOnClickListener(view -> {
                        //预览视频
                        PictureSelector.create(mActivity).externalPictureVideo(images.get(0).getPath());
                    });
                    break;
                default:
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 上传文件至阿里云
     *
     * @param filePath 文件本地路径
     */
    private void uploadFile(String filePath, CallBack callBack) {

        @SuppressLint("AutoDispose") Disposable disposable = Observable
                .create((ObservableOnSubscribe<String>) emitter -> {
                    File file = new File(filePath);
                    OssHelper.getOss(mActivity).putObject(OssHelper.getPutObjectRequest(OssHelper.GS_APP + file.getName(), file.getPath()));
                    String url = OssHelper.getOssPrefixUrl(OssHelper.GS_APP, file.getName());
                    emitter.onNext(url);

                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((String s) -> {
                    if (callBack != null) {
                        callBack.callback(s);
                    }
                }, Throwable::printStackTrace);

    }

    public interface CallBack {
        void callback(String data);
    }

    @Override
    public void onLoadSuccess(String data) {
        hideLoadingDialog();
        ToastUtils.showShort("开通成功");
        finish();
    }

    @Override
    public void onLoadFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort("请先实名认证");
        Intent intent = new Intent(mActivity, PersonalRealNameAc.class);
        startActivity(intent);
    }

    @Override
    public void onLoadRealNameSuccess(RealNameResultBean data) {
        hideLoadingDialog();
        if (data != null) {
            if (data.getGrade() != null) {
                if (data.getGrade().getVoicePrice() != null) {
                    authenticationSucceedName.setText(String.format("语音  【%s蜜豆/分钟】", data.getGrade().getVoicePrice()));
                }
                if (data.getGrade().getVideoPrice() != null) {
                    authenticationSucceedNumber.setText(String.format("视频  【%s蜜豆/分钟】", data.getGrade().getVideoPrice()));
                }
                if (data.getChannel() != null) {
                    List<RealNameResultBean.ChannelBean> channelBeanList = data.getChannel();
                    test = new String[channelBeanList.size()];
                    for (int i = 0; i < test.length; i++) {
                        test[i] = channelBeanList.get(i).getChannelName();
                        if (channelBeanList.get(i).getId() == data.getMl_channel()) {
                            channelIndex = i;
                        }
                    }

                    initTags();
                    searchTagView.setOnTagClickListener((position, tag) -> {
                        channelIndex = position;
                        initTags();
                    });
                }
            }
            if (data.getFilePath() != null) {
                //语音
                String p = data.getFilePath();
                int l = data.getFileLength() / 1000;
                publishAddVoiceTime.setText(l + "″");
                audioUrl = p;
                audioUrlId = data.getId();
                playYime = l + "";
                publishSaveVoice.setVisibility(View.VISIBLE);
                publishDelVoice.setVisibility(View.VISIBLE);
//                openChatUploadingImgAudio.setVisibility(View.GONE);

            }
            if (data.getVideo_details() != null) {
                //视频
                videoUrl = data.getVideo_details();
                openChatUploadingImg.setVisibility(View.VISIBLE);
                GlideHelper.setLoadVideoImage(mActivity, videoUrl, R.color.gray, openChatUploadingImg);
                openChatUploadingImgDel.setVisibility(View.VISIBLE);
                openChatUploadingImg.setOnClickListener(view -> {
                    //预览视频
//                        PictureSelector.create(mActivity).externalPictureVideo(videoUrl);
                    Intent videoIntent = new Intent(mActivity, DisplayVideoAc.class);
                    MyPersonalBean bean = Constant.getSocialUser();
                    videoIntent.putExtra("userId", bean.getUserId() + "");
                    videoIntent.putExtra("video", videoUrl);
//                        videoIntent.putExtra("age",  data.getGrade().getVideoPrice());
                    videoIntent.putExtra("headimg", bean.getHeadimg());
                    videoIntent.putExtra("sex", bean.getSex() + "");
                    videoIntent.putExtra("residence", bean.getResidence());
                    videoIntent.putExtra("name", bean.getGsName());
                    videoIntent.putExtra("money", data.getGrade().getVideoPrice() + "豆/分钟");
                    startActivity(videoIntent);
                });

            }

            if (data.getSounds_video_status() == 1) {
                openChatVoiceImg.setChecked(true);
                openChatVideoImg.setChecked(false);
//                openChatUploadingLint.setVisibility(View.GONE);
                openChatUploadingAudioLint.setVisibility(View.VISIBLE);
            } else if (data.getSounds_video_status() == 2) {
                openChatVideoImg.setChecked(true);
                openChatVoiceImg.setChecked(false);
                openChatUploadingLint.setVisibility(View.VISIBLE);
//                openChatUploadingAudioLint.setVisibility(View.GONE);
            } else {
//                if (data.getFilePath() != null) {
//                    //语音
//                    String p = data.getFilePath();
//                    int l = data.getFileLength() / 1000;
//                    publishAddVoiceTime.setText(l + "″");
//                    audioUrl = p;
//                    audioUrlId = data.getId();
//                    playYime = l + "";
//                    publishSaveVoice.setVisibility(View.VISIBLE);
//                    publishDelVoice.setVisibility(View.VISIBLE);
//                }

                openChatVoiceImg.setChecked(false);
                openChatVideoImg.setChecked(false);
            }
        }

    }

    @Override
    public void onLoadRealNameFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort(msg + "");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1001) {
            //方式一校验
            boolean isHasAudioPermission = CheckAudioPermission.isHasPermission(this);
            Log.i(TAG, "申请权限完毕,当前录音权限:" + isHasAudioPermission);
            //方式二校验
            int result = 0;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    result++;
                }
            }
            if (result != permissions.length) {
                //没有权限
                showBottomToast("请先允许录音权限,请前往设置界面打开录音权限!");
                Log.i(TAG, "onRequestPermissionsResult: 申请权限完毕,当前录音权限:false");
                return;
            }

        }
    }
}
